package com.client.ryt.basic;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import com.client.ryt.task.http.HttpManager;
import com.client.ryt.widget.progressdialog.CustomProgressDialog;

/**
 * Created by Administrator on 2014/12/26.
 */
public class BaseTask<T1 extends BaseRequest,T2 extends BaseResponse> extends AsyncTask<String,Integer,BaseResponse> {
    protected BaseActivity activity;
    protected BaseParameters parameters;
    protected BaseLiteners.BaseResponseListener listener;
    protected Boolean withHint;
    protected Class<T1> request;
    protected Class<T2> response;
    protected String hintMsg;


    public BaseTask(BaseActivity activity,Class<T1> request,Class<T2> response,BaseParameters parameters){
        this(activity,request,response,parameters,null,true);
    }
    public BaseTask(BaseActivity activity,Class<T1> request,Class<T2> response,BaseParameters parameters,BaseLiteners.BaseResponseListener listener){
        this(activity,request,response,parameters,listener,true);
    }
    public BaseTask(BaseActivity activity,Class<T1> request,Class<T2> response,BaseParameters parameters,BaseLiteners.BaseResponseListener listener,Boolean withHint){
        this(activity,request,response,parameters,listener,withHint,"请求中...");
    }
    public BaseTask(BaseActivity activity,Class<T1> request,Class<T2> response,BaseParameters parameters,BaseLiteners.BaseResponseListener listener,Boolean withHint,String hintMsg){
        this.activity = activity;
        this.parameters = parameters;
        this.listener = listener;
        this.withHint = withHint;
        this.request = request;
        this.response = response;
        this.hintMsg = hintMsg;
    }

    @Override
    protected void onPreExecute() {

        if(this.activity != null && this.withHint){
            this.activity.startProgressDialog();
        }
        super.onPreExecute();
    }

    @Override
    protected BaseResponse doInBackground(String... strings) {
       BaseRequest request = HttpManager.buildRequest(this.request,parameters);
       return HttpManager.buildResponse(response,request);
    }

    @Override
    protected void onPostExecute(BaseResponse baseResponse) {
        if(this.activity != null && this.withHint){
            this.activity.stopProgressDialog();
        }
        if(baseResponse != null){
            if(listener != null) {
                if(baseResponse.getIsSuccess()){
                    listener.OnSuccess(baseResponse);
                }else{
                    listener.OnFail(baseResponse.getBaseException());
                }
            }
        }
        super.onPostExecute(baseResponse);
    }

    public BaseActivity getActivity() {
        return activity;
    }

}
